﻿using System;
using System.Windows.Data;

namespace WhiteFlow.DevTrackingTool.UI.Converters
{
    public class TimeSpanConverter : IValueConverter
    {
        private string defaultTimeString;
        private TimeSpan defaultTime;
            
        public TimeSpanConverter()
        {
            defaultTimeString = "00:00";
            defaultTime = new TimeSpan(0, 0, 0);
        }

        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            if (value == null || (value.GetType() != typeof(TimeSpan)))
            {
                return defaultTimeString;
            }

            TimeSpan time = (TimeSpan)value;

            string hours = time.Hours.ToString().PadLeft(2, '0');
            string minutes = time.Minutes.ToString().PadLeft(2, '0');

            return String.Format("{0}:{1}", hours, minutes);
        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            if (value == null)
            {
                return defaultTime;
            }

            TimeSpan time;

            if (TimeSpan.TryParse(value.ToString(), out time))
            {
                return time;
            }
            else
            {
                return defaultTime;
            }
        }
    }
}